/**
 * 用户管理业务
 */


class User {
    // 创建
    async create(ctx) {
        const { server, params } = ctx;
        const tUser = await server.model.User.create(params)
        return tUser.toJSON();
    }
    // 修改
    async update(ctx) {
        const { server, params } = ctx;
        const { pk, ...data } = params;
        const tUser = await server.model.User.findByPk(pk)
        if (tUser === null) {
            return 404;
        }
        const result = await tUser.update(data)
        return result.toJSON();
    }
    // 删除
    async delete(ctx) {
        const { server, params } = ctx;
        const { pk, ...data } = params;
        const tUser = await server.model.User.findByPk(pk)
        if (tUser === null) {
            return 404;
        }
        if (tUser.administrator) {
            return 403;
        }
        const result = await tUser.destroy(data)
        return result.toJSON();
    }
    // 查询
    async find(ctx) { 
        const { server, params } = ctx;
        const { pk } = params;
        const tUser = await server.model.User.findByPk(pk)
        if (tUser === null) {
            return 404;
        }
        return tUser.toJSON();
    }
    // 查询全部
    async findAll(ctx) { 
        const { server } = ctx;
        const _tUser = await server.model.User.findAll()
        const tUser = []
        _tUser.forEach((item) => {
            tUser.push(item.toJSON())
        })
        return tUser;
    }
}

export default User